package fun.carliels.doraemon.common.crypto;

import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5 加密
 */
public class MD5 {

    private static final Logger log = LoggerFactory.getLogger(MD5.class);

    /**
     * 加密
     * @param plainText 明文
     * @param charset 明文编码
     * @return
     */
    public static final String encrypt(String plainText, Charset charset) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            return Hex.encodeHexString(md5.digest(plainText.getBytes(charset)));
        } catch (NoSuchAlgorithmException e) {
            log.error("encrypt exception:{}", e);
            return null;
        }
    }

    /**
     * 加密，默认UTF-8编码
     * @param plainText
     * @return
     */
    public static final String encrypt(String plainText) {
        return encrypt(plainText, StandardCharsets.UTF_8);
    }
}
